const TOKEN_KEY = 'token';
const TOKEN_UKEY = 'tokenU';
const TOKEN_CREATION_TIME_KEY = 'tokenCreationTime';

// 判断用户是否登录
const isLogin = () => {
  return !!localStorage.getItem(TOKEN_KEY);
};

// 获取 token
const getToken = () => {
  return localStorage.getItem(TOKEN_KEY);
};

// 设置 token 并记录创建时间
const setToken = (token: string) => {
  localStorage.setItem(TOKEN_KEY, token);
  // setTokenCreationTime();
};

// 设置 token 创建时间
const setTokenCreationTime = () => {
  localStorage.setItem(TOKEN_CREATION_TIME_KEY, Date.now().toString());
};

// 获取 token 创建时间
const getTokenCreationTime = () => {
  const creationTime = localStorage.getItem(TOKEN_CREATION_TIME_KEY);
  return creationTime? parseInt(creationTime, 10) : null;
};

// 设置另一个 token（可能是刷新 token 等）
const setTokenU = (token: string) => {
  localStorage.setItem(TOKEN_UKEY, token);
};

// 清除 token 及其创建时间
const clearToken = () => {
  localStorage.removeItem(TOKEN_KEY);
  localStorage.removeItem(TOKEN_CREATION_TIME_KEY);
};

// 清除另一个 token
const clearTokenU = () => {
  localStorage.removeItem(TOKEN_UKEY);
};

// 解析 JWT 获取过期时间
const getTokenExpiration = (token: string) => {
  try {
    const base64Url = token.split('.')[1];
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    const jsonPayload = decodeURIComponent(atob(base64).split('').map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join(''));
    const { exp } = JSON.parse(jsonPayload);
    return exp * 1000;
  } catch (error) {
    console.error('解析 token 过期时间失败:', error);
    return null;
  }
};

export {
  isLogin,
  getToken,
  setToken,
  clearToken,
  clearTokenU,
  setTokenU,
  getTokenCreationTime,
  getTokenExpiration,
  setTokenCreationTime
};